package com.zzj.filedownloader.download;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.tencent.bugly.BuglyStrategy;
import com.zzj.filedownloader.download.dbcontrol.DataKeeper;
import com.zzj.filedownloader.download.dbcontrol.FileHelper;
import com.zzj.filedownloader.download.dbcontrol.bean.SQLDownLoadInfo;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;
import net.lingala.zip4j.util.InternalZipConstants;

/* loaded from: classes2.dex */
public class DownLoader {
    private DataKeeper datakeeper;
    private long downFileSize;
    private DownLoadThread downLoadThread;
    private DownLoadSuccess downloadsuccess;
    private long fileSize;
    Handler handler;
    private boolean isSupportBreakpoint;
    private ThreadPoolExecutor pool;
    private SQLDownLoadInfo sqlDownLoadInfo;
    private int TASK_START = 0;
    private int TASK_STOP = 1;
    private int TASK_PROGESS = 2;
    private int TASK_ERROR = 3;
    private int TASK_SUCCESS = 4;
    private final String TEMP_FILEPATH = FileHelper.getTempDirPath();
    private int downloadtimes = 0;
    private int maxdownloadtimes = 5;
    private boolean ondownload = false;
    private HashMap<String, DownLoadListener> listenerMap = new HashMap<>();

    /* loaded from: classes2.dex */
    public interface DownLoadSuccess {
        void onTaskSeccess(String str);
    }

    static /* synthetic */ int access$1008(DownLoader downLoader) {
        int i = downLoader.downloadtimes;
        downLoader.downloadtimes = i + 1;
        return i;
    }

    public DownLoader(Context context, SQLDownLoadInfo sQLDownLoadInfo, ThreadPoolExecutor threadPoolExecutor, boolean z, boolean z2) {
        this.isSupportBreakpoint = false;
        this.fileSize = 0L;
        this.downFileSize = 0L;
        this.isSupportBreakpoint = z;
        this.pool = threadPoolExecutor;
        this.fileSize = sQLDownLoadInfo.getFileSize();
        this.downFileSize = sQLDownLoadInfo.getDownloadSize();
        this.datakeeper = new DataKeeper(context);
        this.sqlDownLoadInfo = sQLDownLoadInfo;
        this.handler = new Handler(context.getMainLooper()) { // from class: com.zzj.filedownloader.download.DownLoader.1
            @Override // android.os.Handler
            public void handleMessage(Message message) {
                if (message.what == DownLoader.this.TASK_START) {
                    DownLoader.this.startNotice();
                } else if (message.what == DownLoader.this.TASK_STOP) {
                    DownLoader.this.stopNotice();
                } else if (message.what == DownLoader.this.TASK_PROGESS) {
                    DownLoader.this.onProgressNotice();
                } else if (message.what == DownLoader.this.TASK_ERROR) {
                    DownLoader.this.errorNotice();
                } else if (message.what == DownLoader.this.TASK_SUCCESS) {
                    DownLoader.this.successNotice();
                }
            }
        };
        if (z2) {
            saveDownloadInfo();
        }
    }

    public String getTaskID() {
        return this.sqlDownLoadInfo.getTaskID();
    }

    public void start() {
        if (this.downLoadThread == null) {
            this.downloadtimes = 0;
            this.ondownload = true;
            this.handler.sendEmptyMessage(this.TASK_START);
            this.downLoadThread = new DownLoadThread();
            this.pool.execute(this.downLoadThread);
        }
    }

    public void stop() {
        DownLoadThread downLoadThread = this.downLoadThread;
        if (downLoadThread != null) {
            this.ondownload = false;
            downLoadThread.stopDownLoad();
            this.pool.remove(this.downLoadThread);
            this.downLoadThread = null;
        }
    }

    public void setDownLoadListener(String str, DownLoadListener downLoadListener) {
        if (downLoadListener == null) {
            removeDownLoadListener(str);
        } else {
            this.listenerMap.put(str, downLoadListener);
        }
    }

    public void removeDownLoadListener(String str) {
        if (this.listenerMap.containsKey(str)) {
            this.listenerMap.remove(str);
        }
    }

    public void setDownLodSuccesslistener(DownLoadSuccess downLoadSuccess) {
        this.downloadsuccess = downLoadSuccess;
    }

    public void destroy() {
        DownLoadThread downLoadThread = this.downLoadThread;
        if (downLoadThread != null) {
            downLoadThread.stopDownLoad();
            this.downLoadThread = null;
        }
        this.datakeeper.deleteDownLoadInfo(this.sqlDownLoadInfo.getTaskID());
        File file = new File(this.TEMP_FILEPATH + this.sqlDownLoadInfo.getFileName());
        if (file.exists()) {
            file.delete();
        }
    }

    public boolean isDownLoading() {
        return this.ondownload;
    }

    public SQLDownLoadInfo getSQLDownLoadInfo() {
        this.sqlDownLoadInfo.setDownloadSize(this.downFileSize);
        return this.sqlDownLoadInfo;
    }

    public void setSupportBreakpoint(boolean z) {
        this.isSupportBreakpoint = z;
    }

    /* loaded from: classes2.dex */
    class DownLoadThread extends Thread {
        private InputStream inputStream;
        private RandomAccessFile localFile;
        private URL url;
        private HttpURLConnection urlConn;
        private int progress = -1;
        private boolean isdownloading = true;

        public DownLoadThread() {
        }

        @Override // java.lang.Thread, java.lang.Runnable
        public void run() {
            while (DownLoader.this.downloadtimes < DownLoader.this.maxdownloadtimes) {
                try {
                    try {
                    } catch (Exception e) {
                        Log.d("zzj", "isdownloading:" + this.isdownloading + ",downloadtimes=" + DownLoader.this.downloadtimes);
                        if (!this.isdownloading) {
                            DownLoader.this.downloadtimes = DownLoader.this.maxdownloadtimes;
                        } else if (DownLoader.this.isSupportBreakpoint) {
                            DownLoader.access$1008(DownLoader.this);
                            if (DownLoader.this.downloadtimes >= DownLoader.this.maxdownloadtimes) {
                                if (DownLoader.this.fileSize > 0) {
                                    DownLoader.this.saveDownloadInfo();
                                }
                                DownLoader.this.pool.remove(DownLoader.this.downLoadThread);
                                DownLoader.this.downLoadThread = null;
                                DownLoader.this.ondownload = false;
                                DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_ERROR);
                            }
                        } else {
                            DownLoader.this.downFileSize = 0L;
                            DownLoader.this.downloadtimes = DownLoader.this.maxdownloadtimes;
                            DownLoader.this.ondownload = false;
                            DownLoader.this.downLoadThread = null;
                            DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_ERROR);
                        }
                        e.printStackTrace();
                        try {
                            if (this.urlConn != null) {
                                this.urlConn.disconnect();
                            }
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                        try {
                            if (this.inputStream != null) {
                                this.inputStream.close();
                            }
                        } catch (Exception e3) {
                            e3.printStackTrace();
                        }
                        if (this.localFile != null) {
                            this.localFile.close();
                        }
                    }
                    if (DownLoader.this.downFileSize == DownLoader.this.fileSize && DownLoader.this.fileSize > 0) {
                        DownLoader.this.ondownload = false;
                        Message message = new Message();
                        message.what = DownLoader.this.TASK_PROGESS;
                        message.arg1 = 100;
                        DownLoader.this.handler.sendMessage(message);
                        DownLoader.this.downloadtimes = DownLoader.this.maxdownloadtimes;
                        DownLoader.this.downLoadThread = null;
                        try {
                            if (this.urlConn != null) {
                                this.urlConn.disconnect();
                            }
                        } catch (Exception e4) {
                            e4.printStackTrace();
                        }
                        try {
                            if (this.inputStream != null) {
                                this.inputStream.close();
                            }
                        } catch (Exception e5) {
                            e5.printStackTrace();
                        }
                        try {
                            if (this.localFile != null) {
                                this.localFile.close();
                                return;
                            }
                            return;
                        } catch (Exception e6) {
                            e6.printStackTrace();
                            return;
                        }
                    }
                    this.url = new URL(DownLoader.this.sqlDownLoadInfo.getUrl());
                    Log.i("wewewe", "run: " + this.url);
                    this.urlConn = (HttpURLConnection) this.url.openConnection();
                    this.urlConn.setConnectTimeout(BuglyStrategy.a.MAX_USERDATA_VALUE_LENGTH);
                    this.urlConn.setReadTimeout(45000);
                    Log.d("zzj", "fileSize:" + DownLoader.this.fileSize + ",downFileSize=" + DownLoader.this.downFileSize + ",isdownloading=" + this.isdownloading);
                    if (DownLoader.this.fileSize < 1) {
                        openConnention();
                    } else {
                        if (new File(DownLoader.this.TEMP_FILEPATH + DownLoader.this.sqlDownLoadInfo.getFileName()).exists()) {
                            this.localFile = new RandomAccessFile(DownLoader.this.TEMP_FILEPATH + DownLoader.this.sqlDownLoadInfo.getFileName(), InternalZipConstants.WRITE_MODE);
                            this.localFile.seek(DownLoader.this.downFileSize);
                            this.urlConn.setRequestProperty("Range", "bytes=" + DownLoader.this.downFileSize + "-");
                        } else {
                            DownLoader.this.fileSize = 0L;
                            DownLoader.this.downFileSize = 0L;
                            DownLoader.this.saveDownloadInfo();
                            openConnention();
                        }
                    }
                    this.inputStream = this.urlConn.getInputStream();
                    long j = DownLoader.this.downFileSize;
                    while (j > 0) {
                        long skip = this.inputStream.skip(j);
                        Log.d("zzj", "at:" + j + ",amt=" + skip);
                        if (skip == 0) {
                            break;
                        }
                        j -= skip;
                    }
                    byte[] bArr = new byte[10240];
                    while (true) {
                        int read = this.inputStream.read(bArr);
                        if (read == -1 || !this.isdownloading) {
                            break;
                        }
                        this.localFile.write(bArr, 0, read);
                        DownLoader.this.downFileSize += read;
                        int i = (int) ((DownLoader.this.downFileSize * 100) / DownLoader.this.fileSize);
                        if (i > this.progress) {
                            this.progress = i;
                            DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_PROGESS);
                        }
                    }
                    Log.d("zzj", "downFileSize:" + DownLoader.this.downFileSize);
                    if (DownLoader.this.downFileSize == DownLoader.this.fileSize) {
                        if (DownLoader.this.RenameFile()) {
                            DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_SUCCESS);
                        } else {
                            new File(DownLoader.this.TEMP_FILEPATH + DownLoader.this.sqlDownLoadInfo.getFileName()).delete();
                            DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_ERROR);
                        }
                        DownLoader.this.datakeeper.deleteDownLoadInfo(DownLoader.this.sqlDownLoadInfo.getTaskID());
                        DownLoader.this.downLoadThread = null;
                        DownLoader.this.ondownload = false;
                    } else if (!this.isdownloading) {
                        DownLoader.this.downloadtimes = DownLoader.this.maxdownloadtimes;
                    } else if (DownLoader.this.isSupportBreakpoint) {
                        DownLoader.access$1008(DownLoader.this);
                        if (DownLoader.this.downloadtimes >= DownLoader.this.maxdownloadtimes) {
                            if (DownLoader.this.fileSize > 0) {
                                DownLoader.this.saveDownloadInfo();
                            }
                            DownLoader.this.pool.remove(DownLoader.this.downLoadThread);
                            DownLoader.this.downLoadThread = null;
                            DownLoader.this.ondownload = false;
                            DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_ERROR);
                        }
                    } else {
                        DownLoader.this.downFileSize = 0L;
                        DownLoader.this.downloadtimes = DownLoader.this.maxdownloadtimes;
                        DownLoader.this.ondownload = false;
                        DownLoader.this.downLoadThread = null;
                        DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_ERROR);
                    }
                    try {
                        if (this.urlConn != null) {
                            this.urlConn.disconnect();
                        }
                    } catch (Exception e7) {
                        e7.printStackTrace();
                    }
                    try {
                        if (this.inputStream != null) {
                            this.inputStream.close();
                        }
                    } catch (Exception e8) {
                        e8.printStackTrace();
                    }
                    try {
                        if (this.localFile != null) {
                            this.localFile.close();
                        }
                    } catch (Exception e9) {
                        e9.printStackTrace();
                    }
                } catch (Throwable th) {
                    try {
                        if (this.urlConn != null) {
                            this.urlConn.disconnect();
                        }
                    } catch (Exception e10) {
                        e10.printStackTrace();
                    }
                    try {
                        if (this.inputStream != null) {
                            this.inputStream.close();
                        }
                    } catch (Exception e11) {
                        e11.printStackTrace();
                    }
                    try {
                        if (this.localFile != null) {
                            this.localFile.close();
                        }
                    } catch (Exception e12) {
                        e12.printStackTrace();
                    }
                    throw th;
                }
            }
        }

        public void stopDownLoad() {
            this.isdownloading = false;
            DownLoader downLoader = DownLoader.this;
            downLoader.downloadtimes = downLoader.maxdownloadtimes;
            if (DownLoader.this.fileSize > 0) {
                DownLoader.this.saveDownloadInfo();
            }
            DownLoader.this.handler.sendEmptyMessage(DownLoader.this.TASK_STOP);
        }

        private void openConnention() throws Exception {
            long contentLength = this.urlConn.getContentLength();
            if (contentLength > 0) {
                DownLoader.this.isFolderExist();
                this.localFile = new RandomAccessFile(DownLoader.this.TEMP_FILEPATH + DownLoader.this.sqlDownLoadInfo.getFileName(), InternalZipConstants.WRITE_MODE);
                this.localFile.setLength(contentLength);
                DownLoader.this.sqlDownLoadInfo.setFileSize(contentLength);
                DownLoader.this.fileSize = contentLength;
                if (this.isdownloading) {
                    DownLoader.this.saveDownloadInfo();
                }
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean isFolderExist() {
        try {
            File file = new File(this.TEMP_FILEPATH);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void saveDownloadInfo() {
        if (this.isSupportBreakpoint) {
            this.sqlDownLoadInfo.setDownloadSize(this.downFileSize);
            this.datakeeper.saveDownLoadInfo(this.sqlDownLoadInfo);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void startNotice() {
        if (this.listenerMap.isEmpty()) {
            return;
        }
        for (DownLoadListener downLoadListener : this.listenerMap.values()) {
            downLoadListener.onStart(getSQLDownLoadInfo());
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void onProgressNotice() {
        if (this.listenerMap.isEmpty()) {
            return;
        }
        for (DownLoadListener downLoadListener : this.listenerMap.values()) {
            downLoadListener.onProgress(getSQLDownLoadInfo(), this.isSupportBreakpoint);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void stopNotice() {
        if (!this.isSupportBreakpoint) {
            this.downFileSize = 0L;
        }
        if (this.listenerMap.isEmpty()) {
            return;
        }
        for (DownLoadListener downLoadListener : this.listenerMap.values()) {
            downLoadListener.onStop(getSQLDownLoadInfo(), this.isSupportBreakpoint);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void errorNotice() {
        if (this.listenerMap.isEmpty()) {
            return;
        }
        for (DownLoadListener downLoadListener : this.listenerMap.values()) {
            downLoadListener.onError(getSQLDownLoadInfo());
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void successNotice() {
        if (!this.listenerMap.isEmpty()) {
            for (DownLoadListener downLoadListener : this.listenerMap.values()) {
                downLoadListener.onSuccess(getSQLDownLoadInfo());
            }
        }
        DownLoadSuccess downLoadSuccess = this.downloadsuccess;
        if (downLoadSuccess != null) {
            downLoadSuccess.onTaskSeccess(this.sqlDownLoadInfo.getTaskID());
        }
    }

    public boolean RenameFile() {
        File file = new File(this.sqlDownLoadInfo.getFilePath());
        if (file.exists()) {
            file.delete();
        }
        File file2 = new File(this.TEMP_FILEPATH + this.sqlDownLoadInfo.getFileName());
        String filePath = this.sqlDownLoadInfo.getFilePath();
        File file3 = new File(filePath.substring(0, filePath.lastIndexOf(InternalZipConstants.ZIP_FILE_SEPARATOR)));
        if (!file3.exists()) {
            file3.mkdirs();
        }
        return file2.renameTo(file);
    }
}
